package com.iot.modbus.manager;

import com.iot.modbus.builder.ReaderSessionFactoryBuilder;
import com.iot.modbus.factory.ReaderSessionFactory;
import com.iot.modbus.reader.ReaderSession;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.IpParameters;
import com.serotonin.modbus4j.msg.ModbusRequest;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ReaderSessionManager {

    private static final Map<String, ReaderSession> sessionMap = new ConcurrentHashMap<>();

    private static final ReaderSessionFactoryBuilder readerSessionFactoryBuilder = new ReaderSessionFactoryBuilder();

    private static final ReaderSessionFactory readerSessionFactory = readerSessionFactoryBuilder.build();

    private static String getKey(final IpParameters ipParameters) {
        return ipParameters.getHost() + "<>" + ipParameters.getPort();
    }


    public static ReaderSession add(IpParameters ipParameters) {
        ReaderSession readerSession = readerSessionFactory.createReaderSession(ipParameters);;
        sessionMap.put(getKey(ipParameters), readerSession);
        return readerSession;
    }

    public static ReaderSession remove(IpParameters ipParameters) {
        return sessionMap.remove(getKey(ipParameters));
    }

    public static ReaderSession get(IpParameters ipParameters) {
        if (!sessionMap.containsKey(getKey(ipParameters))) {
            return add(ipParameters);
        }
        return sessionMap.get(getKey(ipParameters));
    }

    /**
     *
     * @param slaveId
     * @param range
     *      1:线圈状态（单比特值）.2:离散输入状态（只读单比特值）.3:保持寄存器（可读写的多字节值）.4:输入寄存器（只读的多字节值）。
     * @param offset
     * @param length
     * @return
     */
    public static ModbusRequest createReadRequest(int slaveId, int range, int offset, int length) throws ModbusTransportException {
        return readerSessionFactory.createReadRequest(slaveId,range,offset,length);
    }

}
